# -------------------------------------------
# - MoteConfig.py
#
# - Generates a mapping between IR codes and
# - the common remote buttons, by parsing a 
# - lirc remote control file.
# -------------------------------------------


# Imports
#--------------------------------------------

import sys, os, re

import Logger


# Classes
#--------------------------------------------

class MoteConfig:

    #The remote control configuration file to be parsed
    srcfile = ""

    """
    The Constructor.
    """
    def __init__(self,srcfile):
        self.srcfile = srcfile
        Logger.printLog("Config file: "+self.srcfile)
        
    """
    This method parses the configuration file.
    It does look for some common usage errors but assumes
    a syntactically correct file.
    """
    def parse(self):
        
        #Defaults
        optdb={'custom_cmds':{}, #A dictionary of commands to run indexed by string from remote
               'lirc_cmds':{}, #A dictionary of lirc commands [IRCODE, COMMAND] indexed by string from remote
               'port':21567,
               'host':'localhost',
               'remote':'mceusb'}
        
        if (len(self.srcfile) == 0):
            Logger.printLog("No configuration file was specified!")
        
        #open file
        openfile = open(self.srcfile, 'r')
        
        for line in openfile.readlines():
            
            line = line.strip()
            
            #skip empty lines and comments
            if len(line) == 0 or line[:1] == '#':
                continue
            
            #A list of space seperated elements
            linesplit = line.split()
            
            #Look for a captialised item at the start. 
            #These are non-button-map config elements
            if  re.match('[A-Z]', linesplit[0][0]):
                
                if linesplit[0] == 'PORT':
                    optdb['port'] = int(linesplit[1])
                    
                if linesplit[0] == 'HOST':
                    optdb['host'] = linesplit[1]
                
                if linesplit[0] == 'REMOTE_TYPE':
                    optdb['remote'] = linesplit[1]

                if linesplit[0] == 'XSESSION':
                    optdb['xsession'] = linesplit[1]
                    
                if linesplit[0] == 'CODE':
                    this_custom_cmd=linesplit[3]
                    it = 4
                    while ( it < len(linesplit) ):
                        this_custom_cmd= this_custom_cmd + " " + linesplit[it]
                        it=it+1
                    optdb['custom_cmds'][linesplit[1]] = this_custom_cmd

                continue
            
            #Lirc button map
            optdb['lirc_cmds'][linesplit[0]] = linesplit[2], linesplit[3]
                
            
        Logger.printLog("Config file parsed.")
        return optdb
